<template>
	<view class="content">
		<u-navbar :fixed="false" title="派工单" :autoBack="true" :safeAreaInsetTop="true" leftIconColor="#fff"></u-navbar>

		<view class="MainBox">
			<u--form labelPosition="left" :model="formData" :rules="rules" ref="uForm">
				<!-- <u-form-item labelWidth="100" label="工单编号" borderBottom leftIcon="order" :leftIconStyle="{'font-size':'20px'}">
					<u--input v-model="formData.BillNO" placeholder="自动生成" readonly border="none"></u--input>
				</u-form-item> -->

				<u-form-item labelWidth="100" label="派工日期" prop="BillDate" borderBottom leftIcon="file-text" required
					@click="ChoiceTime('BillDate')" :leftIconStyle="{'font-size':'20px'}">
					<u--input v-model="formData.BillDate" disabled disabledColor="#ffffff" placeholder="请选择"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>

				<u-form-item labelWidth="100" label="派工类型" prop="TypeName" borderBottom leftIcon="file-text" required
					@click="openBaseScreen('派工类型','radio')" :leftIconStyle="{'font-size':'20px'}">
					<u--input v-model="formData.TypeName" disabled disabledColor="#ffffff" placeholder="请选择"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>

				<u-form-item labelWidth="100" label="来源工单" prop="BillNO" borderBottom leftIcon="file-text" required
					@click="openBaseScreen('来源工单','radio')" :leftIconStyle="{'font-size':'20px'}">
					<u--input v-model="formData.BillNO" disabled disabledColor="#ffffff" placeholder="请选择"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>

				<u-form-item labelWidth="100" label="产品名称" borderBottom leftIcon="file-text"
					:leftIconStyle="{'font-size':'20px'}">
					<u--input v-model="formData.ProductName" disabled disabledColor="#ffffff" border="none"></u--input>
				</u-form-item>

				<u-form-item labelWidth="100" label="产品规格" borderBottom leftIcon="file-text"
					:leftIconStyle="{'font-size':'20px'}">
					<u--input v-model="formData.ProductSpec" disabled disabledColor="#ffffff" border="none"></u--input>
				</u-form-item>

				<u-form-item labelWidth="100" label="计划数" prop="FPlanQty" borderBottom leftIcon="coupon" required
					:leftIconStyle="{'font-size':'20px'}">
					<u--input v-model="formData.FPlanQty" type="number" placeholder="请输入" border="none"></u--input>
					<u-icon slot="right" name="edit-pen-fill"></u-icon>
				</u-form-item>

				<u-form-item labelWidth="100" label="工艺路线" prop="Routing" borderBottom leftIcon="share" required
					@click="openBaseScreen('工艺路线','other')" :leftIconStyle="{'font-size':'20px'}">
					<u--input v-model="formData.Routing" disabled disabledColor="#ffffff" placeholder="请选择"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>


				<!-- 起止时间 -->
				<u-form-item labelWidth="100" leftIcon="calendar" borderBottom :leftIconStyle="{'font-size':'20px'}">
					<view class="ChoiceTimesBox">

						<view class="TimeBox">

							<view class="StartTime timer" @click="ChoiceTime('start')">
								<!-- <view class="TimeText"> -->
								<text>计划开始时间</text>
								<text>{{dateFormat(formData.DueStartDate) }}</text>
								<!-- </view> -->
							</view>

							<view class="Icon">
								<u-icon name="minus" size="30"></u-icon>
							</view>

							<view class="EndTime timer" @click="ChoiceTime('end')">
								<!-- <view class="TimeText"> -->
								<text>计划结束时间</text>
								<text>{{dateFormat(formData.DueEndDate)}}</text>
								<!-- </view> -->
							</view>
						</view>
					</view>
				</u-form-item>

				<!-- <u-form-item labelWidth="100" label="工作中心" prop="FWorkshopName" borderBottom leftIcon="file-text" required
					@click="openBaseScreen('工作中心','radio')" :leftIconStyle="{'font-size':'20px'}">
					<u--input v-model="formData.FWorkshopName" disabled disabledColor="#ffffff" placeholder="请选择"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item> -->

			</u--form>

			<u-sticky style="background-color: #fff;">

				<m-field style="flex: 1;" valueFontSize="14px" labelWidth="100rpx" labelFontSize="14px" paddings="14rpx"
					borderColor="#dcdcdc" label="是否指派">
					<template v-slot:custom-value>
						<u-switch v-model="assignVal" @change="changeAssign"></u-switch>
					</template>
				</m-field>
				<view v-if="assignVal"
					style="background-color: #fff;width: 100%;overflow: auto;padding: 20rpx 0 10rpx;">
					<u-steps :current="stepsCurrent">
						<u-steps-item style="min-width: 100rpx;" v-for="(item,index) in RoutingData" :key="index"
							@click="ChangeCurrent(item,index)" :title="item.ProcedureName"
							:desc="!item.Outsource ? '厂内' :'外协'">
						</u-steps-item>
					</u-steps>
				</view>
			</u-sticky>

			<!-- 派工列表盒子 -->
			<view v-if="assignVal" class="DispatchBox" style="margin-top: 10rpx;padding: 10rpx;">

				<view class="x-f" style="margin-top: 10rpx;padding: 10rpx;">
					<button type="primary" style="width: fit-content;margin-right: 6px !important;" size="mini"
						@click="PushDataToTable">新增</button>
					<button type="warn" style="width: fit-content;" size="mini" @click="DeleteTableCell">删除</button>
				</view>
				<!-- WCQty -->
				<m-table ref="table" width="100%" :font-size="[30,30]" :default-col-width="180"
					first-col-bg-color="#fff" :headers="headers" :contents="tableData" :bottom-computed-fixed="true"
					enable-check="multiple" :height="320 + 'rpx'" :min-height="[50,50]" checker-color="#51d0d0"
					:show-left-and-right-border="true" checker-cell-bg-color="#fff" :computed-col="TableBottom"
					@onCellClick="tableCellClick($event)" @onCheck="onCheckCell($event)"></m-table>




			</view>

			<!-- 时间选择器 -->
			<u-datetime-picker ref="datetimePicker" :title="PickerTitle" :show="showTimePicker" v-model="DatetimeData"
				mode="date" :closeOnClickOverlay="true" @close="ClosePicker" @cancel="ClosePicker"
				@confirm="ConfirmTime" :formatter="formatter"></u-datetime-picker>

			<u-modal :show="showIptModal" :title="ModalTitle" showCancelButton @confirm="IptModalConfirm"
				@cancel="IptModalCancel">
				<view class="slot-content" style="width: 100%;">
					<u--input placeholder="请输入" type="number" focus border="surround" v-model="IptModalVal"></u--input>
				</view>
			</u-modal>
		</view>

		<view class="BottomBox safe_buttom" :style="$utils.disposeSafeBottomFun()">
			<button v-if="ApproveBack('提交')" class="content_bottom_primary_Btn"
				style="width: 90%;margin: 0 auto !important;" @click="DispatchSubmit">提交</button>
			<!-- <button v-if="pageType == 'create'"
				style="background-color: #51d0d0;color: #fff;width: 90%;margin: 0 auto !important;"
				@click="SubmitBtn('create')">创建</button> -->

			<!-- <view v-else-if="pageType == 'edit'"
				style="width: 100%;display: flex;align-items: center;justify-content: flex-end;">
				<button
					style="background-color: #fff;color: #51d0d0;border: 1px solid #51d0d0;width: 20%;margin-left: 10px !important;min-width: 90px;"
					@click="SubmitBtn('edit')">修改</button>
			</view> -->

		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				showIptModal: false, // 表格弹层
				ModalTitle: '', // 拟态框标题
				IptModalVal: '', // 拟态框输入框

				assignVal: false, // 是否指派
				stepsCurrent: 0, // 选中工序

				tableData: [],
				headers: [{
					label: '派工类型',
					key: 'TypeName',
				}, {
					label: '设备',
					key: 'EquipmentName',
				}, {
					label: '分配数',
					key: 'EQFPlanQty',
					bottomComputedFormat: true,
					FormatType: 'price'
				}],
				TableBottom: ['EQFPlanQty'],
				contentIndex: null, // 记录表格行数据

				pageType: 'create',
				formData: {
					BillDate: '', // 派工日期

					TypeName: '',
					TypeCode: '',
					JobDocTypeID: null,

					JobOrderID: '',
					BillNO: '',
					WoOrderID: '',

					ProductName: '',
					ProductID: '',
					ProductSpec: '',

					FPlanQty: 0, // 派工数 

					Routing: '', // 工艺路线显示字段
					FWorkshopID: '',
				},
				rules: {
					TypeName: {
						type: 'string',
						required: true,
						message: '请选择派工类型',
						trigger: ['change']
					},
					BillNO: {
						type: 'string',
						required: true,
						message: '请选择来源工单',
						trigger: ['change']
					},
					FPlanQty: {
						type: 'number',
						required: true,
						message: '请输入计划数',
						trigger: ['blur', 'input']
					},
					Routing: {
						type: 'string',
						required: true,
						message: '请定义工艺路线',
						trigger: ['change'],
					}
				},
				PickerTitle: '',
				showTimePicker: false,
				DatetimeData: Number(new Date()), // 时间选择器时间
				RoutingData: [], // 工艺路线数据

				BtnApprove: [], // 权限数组
			};
		},
		onLoad(option) {
			let that = this;

			let foundNode = null;
			// 获取页面按钮权限
			for (const module of this.$store.state.ModuleInfo_All) {
				if (module.TreeTypeName === '生产管理') {
					for (const node of module.Node) {
						if (node.APFunName === '派工单') {
							foundNode = JSON.parse(JSON.stringify(node));
							break; // 找到后立即退出内层循环  
						}
					}
					if (foundNode) {
						break;
					}
				}
			}

			this.BtnApprove = foundNode['IconApprove'];
			// console.log(option)
			if (this.$utils.isEmpty(option)) { // 新增
				that.formData.BillDate = this.dateFormat();

				// console.log(this.$store.state.TicketModule.CreateTicket_Routing)

				let Param = this.$store.state.TicketModule.CreateTicket_Routing;

				if (!this.$utils.isEmpty(Param)) {

					Param['form']['TypeName'] = '派工单';
					Param['form']['JobDocTypeID'] = 1;

					that.formData = Object.assign(that.formData, Param['form']);

					that.RoutingData = Param['ProgressList'].map(item => {
						return {
							...item,
							TableData: []
						}
					})

					let index = that.RoutingData.findIndex(obj => !obj.Outsource);
					if (index >= 0) {
						that.ChangeCurrent({}, index);
					}

					// 将工艺路线名称数据提取出来 用 '、' 分割
					let GetRouting = Param['ProgressList'].map(item => {
						return item.ProcedureName
					})
					that.formData.Routing = GetRouting.join('、');

				}
			} else {
				// option.JobOrderID
				that.pageType = 'edit';
				that.formData.JobOrderID = option.JobOrderID
				that.GetDispatchInfo('all');
			}


		},
		mounted() {
			let that = this;

			this.$store.commit('ChangeAndSetStateData', {
				Name1: 'BaseScreenParm',
				data: null
			});
			uni.$on('CreateDispatch_Table_Choice', function(ret) {
				if (ret.type == '派工类型') {
					that.tableData[that.contentIndex] = Object.assign(that.tableData[that.contentIndex], ret.data);
				} else if (ret.type == '设备') {
					that.tableData[that.contentIndex] = Object.assign(that.tableData[that.contentIndex], ret.data);
				}
			})

			uni.$on('CreateDispatch_Choice', function(ret) {
				// console.log(ret)
				if (ret.type == '派工类型') {
					// that.formData = that.omit(that.formData, ['BillDate'])
					if (that.pageType == 'create') {
						// that.RoutingData = [];
						// Object.keys(that.formData).forEach((key) => {
						// 	if (!['BillDate', 'DueStartDate', 'DueEndDate'].includes(
						// 			key)) {
						// 		// 检查that.formData[key]的类型，并相应地设置值  
						// 		if (that.formData[key] === null) {
						// 			// 如果为null，则保持为null  
						// 			that.formData[key] = null;
						// 		} else if (Array.isArray(that.formData[key])) {
						// 			// 如果为数组，则清空数组  
						// 			that.formData[key] = [];
						// 		} else if (typeof that.formData[key] === 'object' && that.formData[key] !==
						// 			null) {
						// 			// 如果为对象（且不是null），则清空对象  
						// 			that.formData[key] = {};
						// 		} else if (typeof that.formData[key] === 'number') {
						// 			// 如果为number，则设置为0  
						// 			that.formData[key] = 0;
						// 		} else {
						// 			// 其他情况，设置为空字符串  
						// 			that.formData[key] = '';
						// 		}
						// 	}
						// });
					}


					that.formData = Object.assign(that.formData, ret.data);

				} else if (ret.type == '来源工单') {
					// 清除来源工单带出的派工日期，避免影响到表单数据
					// delete ret.data.BillDate;

					let obj = {
						WoOrderID: ret.data.WoOrderID,
						BillNO: ret.data.BillNO,
						ProductID: ret.data.ProductID,
						ProductName: ret.data.ProductName,
						ProductSpec: ret.data.ProductSpec,
						ProductCode: ret.data.ProductName + '|' + ret.data.ProductSpec,

						FPlanQty: ret.data.KFPlanQty,
					}

					that.formData = Object.assign(that.formData, obj);

					that.GetXGD_JobGetWOProcedure();
				} else if (ret.type == '产品') {
					that.formData = Object.assign(that.formData, ret.data);
				} else if (ret.type == '工艺路线') {

					// 记录数据
					let Data = JSON.parse(JSON.stringify(that.$store.state.BaseScreenParm));
					that.RoutingData = Data;
					console.log(Data)

					// 如果选中的数据，超出工艺长度，设为0
					if (Data.length < that.stepsCurrent) {
						that.stepsCurrent = 0;
					}


					that.tableData = Data[that.stepsCurrent]['TableData']

					// 将工艺路线名称数据提取出来 用 '、' 分割
					let GetRouting = Data.map(item => {
						return item.ProcedureName
					})
					that.formData.Routing = GetRouting.join('、');

					setTimeout(() => {
						that.$refs.uForm.validate();

						// 清除vuex 中工艺路线的数据
						let Obj = {
							Name1: 'BaseScreenParm',
							data: null
						};

						that.$store.commit('ChangeAndSetStateData', Obj);
					}, 300)
				}
				// console.log(that.formData)
			})
		},
		onUnload() {
			uni.$off('CreateDispatch_Choice');
			uni.$off('CreateDispatch_Table_Choice');

		},
		methods: {
			ApproveBack(str) {
				let that = this;
				let Type = false;
				if (that.BtnApprove.length) {
					Type = that.BtnApprove.some(item => {
						return item.MenuName == str
					})
				}

				return Type;
			},
			changeAssign(data) { // 是否指派
				// console.log(this.assignVal)
				// console.log(data)
			},
			IptModalCancel() { // 拟态框取消
				this.showIptModal = false;
				this.ModalTitle = '';
				this.IptModalVal = '';
			},
			IptModalConfirm() { // 拟态框确认
				let that = this;
				that.tableData[that.contentIndex]['EQFPlanQty'] = that.IptModalVal;
				that.$nextTick(() => {
					that.showIptModal = false;
					that.ModalTitle = '';
					that.IptModalVal = '';
				})
			},
			ChangeCurrent(data, index) {
				let that = this;

				// console.log(that.stepsCurrent)

				if (that.RoutingData[index]['Outsource']) {
					return that.$utils.msg(that.RoutingData[index]['ProcedureName'] + '为外协工序，不可指派该道工序')
				}

				that.RoutingData[that.stepsCurrent]['TableData'] = JSON.parse(JSON.stringify(that.tableData));

				setTimeout(() => {
					that.stepsCurrent = index;
					// 赋值选中的表格数据
					that.tableData = that.RoutingData[index].TableData;
				}, 100)
			},
			PushDataToTable() { // 添加数据到表格
				let that = this;
				let WiatData = that.RoutingData[that.stepsCurrent];
				if (WiatData['WCQty'] > 0 && WiatData.TableData.length == 0) {
					// 已报工,且无指派记录，不允许添加
					return that.$utils.msg('该工序【未指派】且【已报工】，不允许添加')
				}

				// console.log(that.RoutingData[that.stepsCurrent])

				let obj = {
					TypeName: '派工单', // 派工类型
					TypeCode: '',
					JobDocTypeID: 1,

					EquipmentID: '',
					EquipmentCode: '',
					EquipmentName: '',
					EquipmentSpec: '',

					EQFPlanQty: '', // 指定计划数量
				}

				that.tableData.push(obj);
			},
			DeleteTableCell() { // 删除按钮-删除表格数据
				console.log(this.tableData)

				// that.RoutingData[that.stepsCurrent]

				this.RoutingData.forEach(item => {
					item['TableData'] = item.TableData.filter(row => !row.checked)
				});
				this.tableData = this.RoutingData[this.stepsCurrent]['TableData'];
				// console.log(this.RoutingData)
			},
			onCheckCell(data) {
				data.data.map(item => {
					if (item.lineData.WCQty > 0) {
						this.$utils.msg('【' + item.lineData.ProcedureName + '】已报工，禁止删除！')

						item.lineData.checked = false;
					}
				})

				let FilterData = data.data.filter(item => item.lineData.WCQty == 0)

				data.data = JSON.parse(JSON.stringify(FilterData));
			},
			tableCellClick(data) { // 点击表格项
				// console.log(data)
				// 记录选中的表格行数据
				this.contentIndex = data.contentIndex;

				switch (data.header) {
					case '设备':
						this.openBaseScreen_Table(data.header)
						break;
					case '派工类型':
						this.openBaseScreen_Table(data.header)
						break;
					case '分配数':
						this.ModalTitle = data.header
						this.IptModalVal = data['lineData'][data['key']];
						this.showIptModal = true;
						break;
					default:
						this.ModalTitle = data.header
						this.IptModalVal = data['lineData'][data['key']];
						this.showIptModal = true;
						break;
				}
			},
			openBaseScreen_Table(str) {
				let obj = {};
				if (str == '设备') {

					obj = {
						allowClear: false,
						cmd: 'PGD_GetEquipment',
						type: str,
						ListeningName: 'CreateDispatch_Table_Choice',
						// multiple: false,
						serverSearch: {
							isPaging: false, //是否分页
							searchKey: 'EquipmentCode', //搜索关键词，应包含在param中
							showText: 'EquipmentCode', //查询结果显示的字段
							// pageIndexStr: 'pageIndex', //分页页码字段，应包含在param中
							// subText: [{
							// 	label: '描述',
							// 	labelKey: 'desc'
							// }],
							ChoiceDataKey: 'EquipmentID',
							ChoiceDataData: this.tableData[this.contentIndex].EquipmentID,
						},
						param: {
							EquipmentTypeID: 0, // 类型ID
							EquipmentCode: '', // 筛选条件
							EquipmentID: 0, // 设备ID
						}
					}
				} else if (str == '派工类型') {
					obj = {
						allowClear: false,
						cmd: 'XGD_JobType',
						type: str,
						ListeningName: 'CreateDispatch_Table_Choice',
						// multiple: false,
						serverSearch: {
							isPaging: false, //是否分页
							// searchKey: 'SearchKey', //搜索关键词，应包含在param中
							showText: 'TypeName', //查询结果显示的字段
							// pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中
							subText: [{
								label: '编号',
								labelKey: 'TypeCode'
							}],
							ChoiceDataKey: 'JobDocTypeID',
							ChoiceDataData: this.tableData[this.contentIndex].JobDocTypeID,
						},
						param: {}
					}
				}
				this.$store.commit('ChangeAndSetStateData', {
					Name1: 'BaseScreenParm',
					data: obj
				})

				uni.navigateTo({
					url: '/commonPage/Tool/baseScreen'
				})
			},
			DispatchSubmit() { // 派工单提交——新
				let that = this;
				that.ChangeCurrent({}, that.stepsCurrent);

				// 1、判断是否指派
				// 2、如果指派，查找表格数据是否有未填项，存在则提示并切换到指定位置

				const Isempty = (val) => {
					return that.$utils.isEmpty(val)
				}

				let Flash = false;
				// let totalEQFPlanQty = 0; // 初始化总和变量  

				for (let [index, item] of this.RoutingData.entries()) {
					// totalEQFPlanQty = 0; // 每次进入新的item时重置总和  


					for (let [ind, row] of item['TableData'].entries()) {
						if (Isempty(row['EquipmentID']) || Isempty(row['EQFPlanQty']) && row['EQFPlanQty'] == 0) {
							// console.log(index)
							// console.log(ind)

							// that.stepsCurrent = index;
							that.$utils.msg('请完善派工信息');

							that.ChangeCurrent({}, index);
							Flash = true;
							break;
						}

						// 如果EQFPlanQty存在且不为0，则加到总和中  
						// if (!Isempty(row['EQFPlanQty']) && parseInt(row['EQFPlanQty'], 10) > 0) {
						// 	totalEQFPlanQty += parseInt(row['EQFPlanQty'], 10);
						// }
					};

					// 检查总和是否超过特定值（例如100）  
					// if (totalEQFPlanQty > 100) { // 假设超过100就给出提示  
					// 	this.$utils.msg('总和超过限制');
					// 	Flash = true; // 设置Flash为true，以便在外层循环中跳出  
					// 	break; // 跳出外层循环  
					// }

					if (Flash) {
						break;
					}
				};

				if (Flash) {
					return
				}
				// console.log(this.RoutingData)
				// return

				that.$utils.showLoading();

				that.$nextTick(() => {

					let EquipmentTypeID = [],
						Outsource = [], // 是否外协
						WoPROCID = [],
						ProcedureID = [],
						EquipmentID = [],
						JobPROCID = [], // 子表主键ID
						JobFWorkshopID = [],
						MoludTypeID = [],
						MoludID = [],
						ProcessRouteID = [],
						LabourCost = [],
						ProcessRouteDeID = [],
						HourGJ = [],
						ManHour = [],
						FProcessMan = [];


					// let FilterRouting = that.RoutingData.filter(item => {
					// 	return !item.Outsource
					// })

					that.RoutingData.forEach(item => {

						// if (!item.Outsource) {
						Outsource.push(item.Outsource ? 1 : 0);
						WoPROCID.push(item.WoPROCID || 0);
						ProcedureID.push(item.ProcedureID || 0);
						EquipmentTypeID.push(item.EquipmentTypeID || 0);
						EquipmentID.push(item.EquipmentID || 0);
						JobFWorkshopID.push(item.FWorkshopID || 0);
						JobPROCID.push(that.$utils.isEmpty(item.JobPROCID) ? 0 : item.JobPROCID);
						MoludTypeID.push(item.MoludTypeID || 0);
						MoludID.push(item.MoludID || 0);
						ProcessRouteID.push(item.ProcessRouteID || 0);
						LabourCost.push(item.LabourCost);
						ProcessRouteDeID.push(item.ProcessRouteDeID || 0);
						HourGJ.push(item.HourGJ);
						ManHour.push(item.ManHour);
						FProcessMan.push(item.EmplID || 0);

						// }
					})

					let type = 'Y-MM-dd';
					let BillDate = new Date();
					if (that.isToday(that.formData.BillDate)) {
						type = 'Y-MM-dd hh:mm:ss';
					} else {
						BillDate = that.formData.BillDate;
					}
					BillDate = that.dateFormat(BillDate, type);


					// 处理子子表数据
					let EQFlowOrder = [],
						EQProcedureID = [],
						EQOutsource = [],
						EQLabourCost = [],
						EQManHour = [],
						EQHourGJ = [],
						EQEquipmentID = [],
						EQMoludID = [],
						EQFPlanQty = [],
						EQJobDocTypeID = [],
						JobPROCAssignEQID = [];

					that.RoutingData.forEach((item, index) => {

						if (!item.Outsource) {
							if (!that.$utils.isEmpty(item.TableData)) {
								item.TableData.forEach(row => {
									EQFlowOrder.push((index + 1));
									EQProcedureID.push(item.ProcedureID);
									EQOutsource.push(0);
									EQLabourCost.push(0);
									EQManHour.push(0);
									EQHourGJ.push(0);
									EQMoludID.push(0);

									EQEquipmentID.push(row.EquipmentID);
									EQFPlanQty.push(row.EQFPlanQty);
									EQJobDocTypeID.push(row.JobDocTypeID);
									JobPROCAssignEQID.push(row.JobPROCAssignEQID ? row
										.JobPROCAssignEQID : 0);
								})
							} else {
								EQFlowOrder.push((index + 1));
								EQProcedureID.push(item.ProcedureID);
								EQOutsource.push(0);
								EQLabourCost.push(0);
								EQManHour.push(0);
								EQHourGJ.push(0);
								EQMoludID.push(0);

								EQEquipmentID.push(0);
								EQFPlanQty.push(0);
								EQJobDocTypeID.push(0);
								JobPROCAssignEQID.push(0);
							}

						}
					})


					let obj = {
						WoOrderID: that.formData.WoOrderID,
						JobDocTypeID: that.formData.JobDocTypeID,
						ProductID: that.formData.ProductID,
						JobOrderID: that.formData.JobOrderID || 0,
						FPlanQty: that.formData.FPlanQty || 0,
						BillDate: BillDate,
						DueStartDate: that.dateFormat(that.formData.DueStartDate),
						DueEndDate: that.dateFormat(that.formData.DueEndDate),
						Outsource: Outsource.join('~'), // 是否外协

						JobPROCID: JobPROCID.join('~'),
						EquipmentTypeID: EquipmentTypeID.join('~'), // 设备类型
						WoPROCID: WoPROCID.join('~'), // 工单工序ID
						ProcedureID: ProcedureID.join('~'), // 工序ID
						EquipmentID: EquipmentID.join('~'), // 设备
						JobFWorkshopID: JobFWorkshopID.join('~'), // 工序车间
						MoludTypeID: MoludTypeID.join('~'), // 模具类型
						MoludID: MoludID.join('~'), // 模具
						ProcessRouteID: ProcessRouteID.join('~'), // 工艺路线主表ID
						LabourCost: LabourCost.join('~'), // 工价
						ProcessRouteDeID: ProcessRouteDeID.join('~'), // 工艺路线子表ID
						HourGJ: HourGJ.join('~'), // 工时工价
						ManHour: ManHour.join('~'), // 工时
						FProcessMan: FProcessMan.join('~'), // 生产人员
						EQFlowOrder: EQFlowOrder.join('~'),
						EQProcedureID: EQProcedureID.join('~'),
						EQOutsource: EQOutsource.join('~'),
						EQLabourCost: EQLabourCost.join('~'),
						EQManHour: EQManHour.join('~'),
						EQHourGJ: EQHourGJ.join('~'),
						EQEquipmentID: EQEquipmentID.join('~'),
						EQMoludID: EQMoludID.join('~'),
						EQFPlanQty: EQFPlanQty.join('~'),
						EQJobDocTypeID: EQJobDocTypeID.join('~'),
						JobPROCAssignEQID: JobPROCAssignEQID.join('~')
					};
					// console.log(obj)

					that.Request.request('XGD_JobSuborUpDte_2', obj, (ret) => {
						// console.log(ret)
						that.$utils.hideLoading();
						if (ret.status == 200) {

							if (ret.data.ds[0].status == 200) {
								that.formData.JobOrderID = ret.data.ds[0].JobOrderID;

								uni.showToast({
									title: '提交成功'
								})
								that.GetDispatchInfo('all');
							} else if (ret.data.ds[0].status == 500) {
								that.$utils.msg(ret.data.ds[0].msg)
								that.formData.JobOrderID = ret.data.ds[0].JobOrderID;
								if (ret.data.ds[0].JobOrderID > 0) {
									that.GetDispatchInfo('form');
								}
							} else {
								that.$utils.msg(ret.data.ds[0].msg)
							}
						}
					}, err => {
						that.$utils.msg('提交失败，请重试');
						that.$utils.hideLoading();
					})

				})
			},

			GetDispatchInfo(str) { // 回显接口，获取详情
				let that = this;

				try {
					that.Request.request('XGD_SelectJonbDetails', {
						JobOrderID: that.formData.JobOrderID
					}, ret => {
						// console.log(ret)
						if (ret.status == 200) {
							ret.data.ds[0]['BillDate'] = that.dateFormat(ret.data.ds[0]['BillDate'],
								'Y-MM-dd hh:mm:ss');

							that.formData = Object.assign(that.formData, ret.data.ds[0]);
							let FunData = JSON.parse(JSON.stringify(ret.data.ds1))
							const FilterData = ret.data.ds1.map(item => item.ProcedureName)

							if (str == 'all') {
								that.formData.Routing = FilterData.join(',');
								// that.RoutingData = ret.data.ds1;
								FunData.forEach(item => {
									item['TableData'] = [];

									ret.data.ds2.forEach(row => {
										row['EQFPlanQty'] = row['FPlanQty'];
										if (item.JobPROCID == row.JobPROCID) {
											item['TableData'].push(row)
										}
									})
								})
								// console.log(FunData)

								// 如果ds2有数据，说明有派工记录，处理派工
								if (ret.data.ds2.length) {
									that.assignVal = true;


									let FilterData_Table = FunData.filter(item => {
										return item.TableData.length
									})

									that.tableData = FilterData_Table[0]['TableData']
								}


								that.RoutingData = FunData;
							}

						}
					}, err => {

					})
				} catch (e) {
					//TODO handle the exception
				}
			},
			GetXGD_JobGetWOProcedure() { // 根据工单ID获取工单工序
				let that = this;

				that.Request.request('XGD_JobGetWOProcedure', {
					WoOrderID: that.formData.WoOrderID
				}, ret => {
					// console.log(ret)
					if (ret.status == 200) {
						that.RoutingData = ret.data.ds;

						let Routing = [];
						ret.data.ds.forEach(item => {
							Routing.push(item.ProcedureName);
						});

						that.formData.Routing = Routing.join(',');

					}
				}, err => {

				})

			},
			openBaseScreen(str, type) { // 前往筛选页
				let that = this;

				if (type == 'radio') {
					let obj = null;
					// let url = '/commonPage/Tool/baseScreen';
					let url = '/commonPage/Tool/baseScreen';
					// console.log(str)
					if (str == '派工类型') {
						obj = {
							allowClear: false,
							cmd: 'XGD_JobType',
							type: str,
							ListeningName: 'CreateDispatch_Choice',
							// multiple: false,
							serverSearch: {
								isPaging: false, //是否分页
								// searchKey: 'SearchKey', //搜索关键词，应包含在param中
								showText: 'TypeName', //查询结果显示的字段
								// pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中
								subText: [{
									label: '编号',
									labelKey: 'TypeCode'
								}],
								ChoiceDataKey: 'JobDocTypeID',
								ChoiceDataData: this.formData.JobDocTypeID,
							},
							param: {}
						}
					} else if (str == '产品') {
						obj = {
							allowClear: false,
							cmd: 'XGD_Product',
							type: str,
							ListeningName: 'CreateDispatch_Choice',
							// multiple: false,
							serverSearch: {
								isPaging: true, //是否分页
								searchKey: 'SearchKey', //搜索关键词，应包含在param中
								showText: 'ProductInfo', //查询结果显示的字段
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中
								subText: [{
									label: '描述',
									labelKey: 'desc'
								}],
								ChoiceDataKey: 'ProductID',
								ChoiceDataData: this.formData.ProductID,
							},
							param: {
								SearchKey: '',
								PageIndex: 1,
								PageSize: 30
							}
						}
					} else if (str == '来源工单') {
						obj = {
							allowClear: false,
							cmd: 'XGD_GetWorkByJobType',
							type: str,
							ListeningName: 'CreateDispatch_Choice',
							// multiple: false,
							serverSearch: {
								isPaging: false, //是否分页
								// searchKey: 'SearchKey', //搜索关键词，应包含在param中
								showText: 'BillNO', //查询结果显示的字段
								// pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中
								subText: [{
									label: '产品',
									labelKey: 'ProductName'
								}, {
									label: '可派数量',
									labelKey: 'KFPlanQty'
								}, ],
								ChoiceDataKey: 'WoOrderID',
								ChoiceDataData: this.formData.WoOrderID,
							},
							param: {
								JobDocTypeID: this.formData.JobDocTypeID
							}
						}
					}

					this.$store.commit('ChangeAndSetStateData', {
						Name1: 'BaseScreenParm',
						data: obj
					})

					uni.navigateTo({
						url: url
					})

				} else if (type == 'other') {
					if (str == '工艺路线') {

						// 将当前工艺路线数据存储到vuex中，方便获取
						let Obj = {
							Name1: 'BaseScreenParm',
							data: {
								RoutingData: this.RoutingData,
								formData: this.formData
							}
						};
						this.$store.commit('ChangeAndSetStateData', Obj);

						uni.navigateTo({
							url: './DispatchRouting'
						})
					}
				}

			},
			formatter(type, value) { // 时间选择器数据格式化
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				return value
			},
			ChoiceTime(type) { // 点击计划时间
				var that = this;
				that.TimeType = type;
				if (type == 'start') {
					that.DatetimeData = Number(that.formData.DueStartDate);
					that.PickerTitle = '计划开始时间';
				} else if (type == 'end') {
					that.DatetimeData = Number(that.formData.DueEndDate);
					that.PickerTitle = '计划结束时间';
				} else if (type == 'BillDate') {
					that.DatetimeData = Number(that.formData.BillDate);
					that.PickerTitle = '派工日期';
				} else {
					that.DatetimeData = Number(new Date());
					that.PickerTitle = '';
				}
				// that.$nextTick(() => {
				setTimeout(() => {
					that.showTimePicker = true;
				}, 300)
				// })
			},
			isToday(dateString) { // 判断是否为当日
				// 假设dateString是一个格式为"YYYY-MM-DD"的字符串  
				const today = new Date();
				const inputDate = new Date(dateString);

				// 清除时间部分  
				today.setHours(0, 0, 0, 0);
				inputDate.setHours(0, 0, 0, 0);

				// 直接比较年份、月份和日期  
				return (
					today.getFullYear() === inputDate.getFullYear() &&
					today.getMonth() === inputDate.getMonth() &&
					today.getDate() === inputDate.getDate()
				);
			},
			dateFormat(val, type = 'Y-MM-dd') { // 格式化时间
				var that = this;
				if (!that.$utils.isEmpty(val)) {
					return that.Request.dateFormat(new Date(val), type);
				} else {
					return that.Request.dateFormat(new Date(), type);
				}
			},
			ClosePicker() { // 关闭时间选择器
				this.DatetimeData = Number(new Date());
				this.showTimePicker = false;
			},
			ConfirmTime(data) { // 确认时间
				// console.log(data.value)

				if (this.TimeType == 'start') {
					this.formData.DueStartDate = data.value;
				} else if (this.TimeType == 'end') {
					this.formData.DueEndDate = data.value;
				} else if (this.TimeType == 'BillDate') {
					this.formData.BillDate = this.dateFormat(data.value);
				}
				this.showTimePicker = false;
			},
			SubmitBtn(str) {
				let that = this;
				// console.log(this.formData)
				console.log(this.RoutingData)
				// return
				this.$refs.uForm.validate().then(res => {

					that.$utils.showLoading();

					let EquipmentTypeID = [],
						Outsource = [], // 是否外协
						WoPROCID = [],
						ProcedureID = [],
						EquipmentID = [],
						JobPROCID = [], // 子表主键ID
						JobFWorkshopID = [],
						MoludTypeID = [],
						MoludID = [],
						ProcessRouteID = [],
						LabourCost = [],
						ProcessRouteDeID = [],
						HourGJ = [],
						ManHour = [],
						FProcessMan = [];

					that.RoutingData.forEach(item => {
						Outsource.push(item.Outsource ? 1 : 0);
						WoPROCID.push(item.WoPROCID || 0);
						ProcedureID.push(item.ProcedureID || 0);
						EquipmentTypeID.push(item.EquipmentTypeID || 0);
						EquipmentID.push(item.EquipmentID || 0);
						JobFWorkshopID.push(item.FWorkshopID || 0);
						JobPROCID.push(that.$utils.isEmpty(item.JobPROCID) ? 0 : item.JobPROCID);
						MoludTypeID.push(item.MoludTypeID || 0);
						MoludID.push(item.MoludID || 0);
						ProcessRouteID.push(item.ProcessRouteID || 0);
						LabourCost.push(item.LabourCost);
						ProcessRouteDeID.push(item.ProcessRouteDeID || 0);
						HourGJ.push(item.HourGJ);
						ManHour.push(item.ManHour);
						FProcessMan.push(item.EmplID || 0);
					})

					let type = 'Y-MM-dd';
					let BillDate = new Date();
					if (this.isToday(that.formData.BillDate)) {
						type = 'Y-MM-dd hh:mm:ss';
					} else {
						BillDate = that.formData.BillDate;
					}
					BillDate = that.dateFormat(BillDate, type);


					let obj = {
						WoOrderID: that.formData.WoOrderID,
						JobDocTypeID: that.formData.JobDocTypeID,
						ProductID: that.formData.ProductID,
						JobOrderID: that.formData.JobOrderID || 0,
						FPlanQty: that.formData.FPlanQty || 0,
						BillDate: BillDate,
						DueStartDate: that.dateFormat(that.formData.DueStartDate),
						DueEndDate: that.dateFormat(that.formData.DueEndDate),
						Outsource: Outsource.join('~'), // 是否外协

						JobPROCID: JobPROCID.join('~'),
						EquipmentTypeID: EquipmentTypeID.join('~'), // 设备类型
						WoPROCID: WoPROCID.join('~'), // 工单工序ID
						ProcedureID: ProcedureID.join('~'), // 工序ID
						EquipmentID: EquipmentID.join('~'), // 设备
						JobFWorkshopID: JobFWorkshopID.join('~'), // 工序车间
						MoludTypeID: MoludTypeID.join('~'), // 模具类型
						MoludID: MoludID.join('~'), // 模具
						ProcessRouteID: ProcessRouteID.join('~'), // 工艺路线主表ID
						LabourCost: LabourCost.join('~'), // 工价
						ProcessRouteDeID: ProcessRouteDeID.join('~'), // 工艺路线子表ID
						HourGJ: HourGJ.join('~'), // 工时工价
						ManHour: ManHour.join('~'), // 工时
						FProcessMan: FProcessMan.join('~'), // 生产人员
					};

					console.log(obj)
					try {
						that.Request.request('XGD_JobSuborUpDte', obj, ret => {
							console.log(ret)
							if (ret.status == 200) {

								// if (str == 'create') {

								// }
								// ret.data.ds[0]['JobOrderID']
								that.$utils.hideLoading();
								uni.showToast({
									title: '保存成功'
								});

								// 接口请求成功后将页面状态改为edit，并调用回显接口
								that.pageType = 'edit';
								that.formData.JobOrderID = ret.data.ds[0]['JobOrderID'];
								that.GetDispatchInfo('all');

								uni.$emit('Refresh_DispatchList');
							}
						}, err => {
							console.log(err)
							that.$utils.hideLoading();
							that.$utils.msg('请求失败，请重试！')
						})
					} catch (e) {
						that.$utils.hideLoading();
						that.$utils.msg('请求失败，请重试！')
						//TODO handle the exception
					}


				}).catch(errors => {
					// uni.$u.toast('校验失败')
					console.log(errors)
				})
			},
		}
	}
</script>

<style lang="scss">
	.content {
		display: flex;
		flex-direction: column;
		height: 100vh;
		// height: calc(100vh - 60px);
		background-color: #f9f9f9;

		uni-button {
			margin-left: initial !important;
			margin-right: initial !important;
		}

		.MainPopup {
			flex: initial !important;

			.PopupContent {
				display: flex;
				flex-direction: column;
				min-height: 240px;
				width: 90vw;
			}

			.u-transition {
				z-index: 99999 !important;
			}


			.PopupMainBox {
				padding: 12px 10px 6px;
				flex: 1;
				// overflow: auto;

				.CellBox {
					margin-bottom: 20px;

					.LeftBox {
						font-size: 14px;
						color: #999;
						margin-right: 10px;
					}
				}

				.uni-input-placeholder {
					color: #6a6a6a !important;
					font-size: 12px !important;
				}
			}

			.PopupBottomBox {
				display: flex;
				align-items: center;
				justify-content: flex-end;
				padding: 10px 10px;

				.CancelBtn {
					background-color: #fff;
					color: #51d0d0;
					border: 1px solid #51d0d0;
					min-width: 80px;
				}

				.ComfirmBtn {
					background-color: #51d0d0;
					color: #fff;
					min-width: 80px;
					margin-left: 10px !important;
				}
			}
		}

		.MainBox {
			flex: 1;
			overflow: auto;
			// padding: 10px;

			// 表单1
			.u-form {
				// padding: 0px 10px;

				.u-form-item {
					background-color: #fff;
					padding: 0 16px;
				}


				.TopOption {

					.u-form-item__body {
						flex-direction: column !important;
					}
				}

				// 起止时间
				.ChoiceTimesBox {
					width: 100%;
					display: flex;
					align-items: center;
					// background-color: #fff;
					// padding: 18px 10px;
					// margin-top: 10px;

					.TimeBox {
						flex: 1;
						display: flex;
						align-items: center;
						justify-content: space-evenly;

						.timer {
							width: 100%;
							flex: 2;
							display: flex;
							flex-direction: column;
							// align-items: center;
							font-size: 16px;
							color: #333;

							text:first-child {
								margin-bottom: 10px;
								font-weight: 600;
							}

							text:last-child {
								height: 20px;
							}
						}

						.Icon {
							flex: 1;
						}
					}
				}


				// 上传-删除图标
				.u-upload__deletable {
					width: 20px;
					height: 20px;

					.u-upload__deletable__icon {
						right: -1px !important;

						.u-icon__icon {
							font-size: 20px !important;
							line-height: 16px !important;
						}
					}
				}
			}
		}

		.BottomBox {
			height: 70px;
			line-height: 70px;
			padding: 6px 15px;
			border-top: 1px solid #efefef;
			display: flex;
			align-items: center;
			background-color: #fff;
		}
	}
</style>